<template>
  <a-layout class="chat-window">
    <!-- 文件管理面板 -->
    <a-layout-sider 
      v-if="showFileManager"
      width="400"
      class="file-manager-sider"
      theme="light"
    >
      <file-manager />
    </a-layout-sider>
    
    <a-layout>
      <a-layout-header class="chat-header">
        <div class="header-content">
          <h3 class="session-title">{{ sessionName }}</h3>
          <div class="header-actions">
            <a-button 
              @click="toggleFileManager" 
              size="small" 
              type="text"
              :class="{ 'active': showFileManager }"
            >
              <template #icon><FolderOutlined /></template>
              文件管理
            </a-button>
            <a-button @click="clearChat" size="small" type="text">
              <template #icon><ClearOutlined /></template>
              清空对话
            </a-button>
          </div>
        </div>
      </a-layout-header>
      
      <a-layout-content class="chat-content">
        <message-list :messages="chatStore.messages" :is-thinking="loading && isStreaming" ref="messageListRef" />
      </a-layout-content>
      
      <a-layout-footer class="chat-footer">
        <a-space class="input-area">
          <a-textarea
            v-model:value="inputText"
            :auto-size="{ minRows: 1, maxRows: 4 }"
            placeholder="输入消息..."
            @pressEnter.prevent="handleSend"
          />
          <a-button
            type="primary"
            :loading="loading"
            @click="handleSend"
            :disabled="isStreaming"
          >
            <template #icon><SendOutlined /></template>
          </a-button>
          <a-button
            v-if="isStreaming"
            type="default"
            danger
            @click="handleStop"
          >
            停止
          </a-button>
          <a-upload
            :customRequest="handleUpload"
            :showUploadList="false"
          >
            <a-button>
              <template #icon><UploadOutlined /></template>
            </a-button>
          </a-upload>
        </a-space>
      </a-layout-footer>
    </a-layout>
  </a-layout>
</template>

<script setup lang="ts">
import { ref, computed, onMounted, onUnmounted } from 'vue'
import { SendOutlined, UploadOutlined, FolderOutlined, ClearOutlined } from '@ant-design/icons-vue'
import { message } from 'ant-design-vue'
import { useChatStore } from '@/stores/chat'
import MessageList from './MessageList.vue'
import FileManager from '@/components/FileManager/FileManager.vue'
import { sendMessage, uploadFile, sendMessageStream, stopGeneration, type StreamChunk } from '@/api/chat'

const chatStore = useChatStore()
const inputText = ref('')
const loading = ref(false)
const showFileManager = ref(false)
const messageListRef = ref()
const isStreaming = ref(false)
const currentStreamingIndex = ref(-1)

// 计算当前会话名称
const sessionName = computed(() => {
  const currentSession = chatStore.sessions.find(s => s.id === chatStore.sessionId)
  return currentSession?.name || '默认会话'
})

// 设置滚动回调函数
onMounted(() => {
  if (messageListRef.value) {
    chatStore.setScrollToBottomCallback(() => {
      messageListRef.value?.scrollToBottom()
    })
  }
})

// 清理回调函数
onUnmounted(() => {
  chatStore.setScrollToBottomCallback(null)
})

const toggleFileManager = () => {
  console.log('toggleFileManager clicked, current state:', showFileManager.value)
  showFileManager.value = !showFileManager.value
  console.log('toggleFileManager new state:', showFileManager.value)
}

const clearChat = () => {
  chatStore.clearMessages()
  message.success('对话已清空')
}

const handleSend = async () => {
  if (!inputText.value.trim() || isStreaming.value) return
  
  loading.value = true
  isStreaming.value = true
  let hasReceivedMeaningfulContent = false
  
  try {
    // 添加用户消息到界面
    chatStore.addMessage({
      type: 'user',
      content: inputText.value
    })
    
    // 添加空的助手消息用于流式更新
    const assistantMessage = {
      type: 'assistant' as const,
      content: ''
    }
    chatStore.addMessage(assistantMessage)
    currentStreamingIndex.value = chatStore.messages.length - 1
    
    const userMessage = inputText.value
    inputText.value = ''
    
    // 使用流式API
    await sendMessageStream(
      userMessage, 
      chatStore.sessionId,
      (chunk: StreamChunk) => {
        // 只有当收到实际有意义的内容时才取消loading状态
        // 检查内容是否为空或只包含空白字符，并且累积内容达到一定长度
        if (loading.value && chunk.chunk && chunk.chunk.trim().length > 0) {
          // 累积当前消息的总长度
          const currentContent = chatStore.messages[currentStreamingIndex.value]?.content || ''
          const totalContent = currentContent + chunk.chunk
          
          // 当累积内容达到一定长度时才取消loading状态，确保AI真正开始输出
          if (totalContent.trim().length >= 3 || hasReceivedMeaningfulContent) {
            loading.value = false
            hasReceivedMeaningfulContent = true
          }
        }
        // 更新流式消息内容
        if (currentStreamingIndex.value >= 0 && currentStreamingIndex.value < chatStore.messages.length) {
          chatStore.messages[currentStreamingIndex.value].content += chunk.chunk
        }
      },
      (error: string) => {
        console.error('Stream error:', error)
        if (currentStreamingIndex.value >= 0 && currentStreamingIndex.value < chatStore.messages.length) {
          chatStore.messages[currentStreamingIndex.value].content = '❌ 发送消息时出现错误，请重试'
        }
        message.error('发送消息失败，请检查网络连接或稍后重试')
        loading.value = false
        isStreaming.value = false
      },
      (timestamp?: string) => {
        // 如果收到时间戳，更新助手消息的时间戳
        if (timestamp && currentStreamingIndex.value >= 0) {
          chatStore.updateMessageTimestamp(currentStreamingIndex.value, timestamp)
        }
        isStreaming.value = false
        currentStreamingIndex.value = -1
        loading.value = false
      },
      () => {
        // onStart回调 - 确保loading状态为true，表示AI正在思考
        console.log('Stream started, AI is thinking...')
        loading.value = true
        isStreaming.value = true
      }
    )
    
  } catch (error) {
    // 移除失败的消息
    if (currentStreamingIndex.value >= 0) {
      chatStore.messages.splice(currentStreamingIndex.value, 1)
    }
    message.error('发送消息失败，请检查网络连接或稍后重试')
    console.error('Chat error:', error)
    isStreaming.value = false
    currentStreamingIndex.value = -1
    loading.value = false
  }
}

const handleStop = async () => {
  try {
    await stopGeneration(chatStore.sessionId)
    isStreaming.value = false
    currentStreamingIndex.value = -1
    
    message.success('已停止生成并清理对话')
  } catch (error) {
    console.error('Stop generation error:', error)
    message.error('停止生成失败')
  } finally {
    loading.value = false
  }
}

const handleUpload = async ({ file }: { file: File }) => {
  const uploadingMessage = message.loading('正在上传文件，请稍候...', 0)
  try {
    const response = await uploadFile(file, chatStore.sessionId)
    uploadingMessage()
    message.success(`文件 ${file.name} 上传成功`)
    
    // 添加文件上传成功的系统消息
    chatStore.addMessage({
      type: 'assistant',
      content: `📎 文件上传成功：${file.name}\n💡 您现在可以询问关于这个文件的问题了！`
    })
  } catch (error) {
    uploadingMessage()
    message.error('文件上传失败，请检查文件格式或稍后重试')
    console.error('Upload error:', error)
  }
}
</script>

<style scoped>
.chat-window {
  height: 100vh;
}

.file-manager-sider {
  border-right: 1px solid #f0f0f0;
  background: #fafafa;
}

.chat-header {
  background: #fff;
  border-bottom: 1px solid #f0f0f0;
  padding: 0 16px;
  height: 64px;
  line-height: 64px;
}

.header-content {
  display: flex;
  justify-content: space-between;
  align-items: center;
  height: 100%;
}

.session-title {
  margin: 0;
  font-size: 16px;
  font-weight: 500;
  color: #262626;
}

.header-actions {
  display: flex;
  gap: 8px;
}

.header-actions .ant-btn.active {
  color: #1890ff;
  background-color: #e6f7ff;
}

.chat-content {
  padding: 24px;
  overflow-y: auto;
  background: #fff;
}

.chat-footer {
  padding: 12px;
  border-top: 1px solid #f0f0f0;
  background: #fff;
}

.input-area {
  width: 100%;
  display: flex;
}

.input-area :deep(.ant-input) {
  flex: 1;
}

/* 响应式设计 */
@media (max-width: 1200px) {
  .file-manager-sider {
    width: 300px !important;
  }
}

@media (max-width: 768px) {
  .file-manager-sider {
    width: 280px !important;
  }
  
  .header-content {
    flex-direction: column;
    height: auto;
    padding: 8px 0;
  }
  
  .session-title {
    font-size: 14px;
    margin-bottom: 4px;
  }
  
  .chat-header {
    height: auto;
    line-height: normal;
    padding: 8px 16px;
  }
}
</style>